package com.yeskery.nut.extend.i18n;

import com.yeskery.nut.core.NutException;
import com.yeskery.nut.core.RequestApplicationContext;
import com.yeskery.nut.util.StringUtils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;

/**
 * 默认的国际化消息服务
 * @author sprout
 * 2022-05-28 16:32
 */
public class DefaultMessageServiceImpl implements MessageService {

    /** 消息资源对象 */
    private final MessageResource messageResource;

    /**
     * 构建默认的消息资源对象
     */
    public DefaultMessageServiceImpl() {
        this.messageResource = new MessageResource();
    }

    /**
     * 构建默认的消息资源对象
     * @param path 路径
     */
    public DefaultMessageServiceImpl(String path) {
        this.messageResource = new MessageResource(path);
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getMessage(String key, Object... params) {
        Object object;
        try {
            object = RequestApplicationContext.getResource(I18nPlugin.I18N_LOCALES);
            if (object == null) {
                return getDynamicMessage(messageResource.getDefaultResource(), key, params);
            }
        } catch (NutException e) {
            return getDynamicMessage(messageResource.getDefaultResource(), key, params);
        }
        Set<Locale> locales = (Set<Locale>) object;
        for (Locale locale : locales) {
            String value = getMessage(locale, key, params);
            if (!StringUtils.isEmpty(value)) {
                return value;
            }
        }

        return getDynamicMessage(messageResource.getDefaultResource(), key, params);
    }

    @Override
    public String getMessage(Locale locale, String key, Object... params) {
        return getDynamicMessage(messageResource.getLocaleResource(locale), key, params);
    }

    /**
     * 获取动态消息
     * @param properties 消息资源
     * @param key 消息key
     * @param params 消息参数
     * @return 动态消息
     */
    private String getDynamicMessage(Properties properties, String key, Object... params) {
        if (properties != null) {
            String value = properties.getProperty(key);
            return StringUtils.isEmpty(value) || params == null || params.length == 0 ? value : MessageFormat.format(value, params);
        }
        return null;
    }
}
